package com.hongsuan.pplive.modules.sys.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.cnjson.common.config.Global;
import com.cnjson.common.utils.DesUtils;

public class MobileApiInterceptor implements HandlerInterceptor {

	private static final String TOKEN_KEY = Global.getTokenKey();
	private static final String sdkAppId = Global.getAppId();
	private static String TOKEN = null;

	private static final String getToken() {
		try {
			System.out.println("--************enter get token!");
			if (TOKEN == null)
				TOKEN = DesUtils.encrypt(TOKEN_KEY + sdkAppId, TOKEN_KEY);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return TOKEN;
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception e)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
		String param = request.getParameter("token");
		if (StringUtils.isBlank(param)) {
			System.out.println("----------------->token is empty!");
			String msg = "token is empty!";
			response.sendRedirect(request.getContextPath()+"/badRequest?code=101&message=" + msg);
			return false;
		}
		String token = getToken();
		if (!token.equals(param)) {
			System.out.println("----------------->token is uncorrect!");
			String msg = "token is uncorrect!";
			response.sendRedirect(request.getContextPath()+"/badRequest?code=102&message=" + msg);
			return false;
		}
		return true;
	}
}
